﻿
Namespace Compiler.Semantic

    ''' <summary>
    ''' Control the semantic analysis environment. Provides the scope operations and symbol table stacks.
    ''' </summary>
    ''' <remarks></remarks>
    Public Class Environment(Of T As Class)
        Private m_symbolTableStack As Stack(Of BindingTable(Of T))

        Public Sub New()
            m_symbolTableStack = New Stack(Of BindingTable(Of T))
        End Sub

        Public ReadOnly Property CurrentTable() As BindingTable(Of T)
            Get
                Return m_symbolTableStack.Peek()
            End Get
        End Property

        Public Sub BeginScope()
            m_symbolTableStack.Push(New BindingTable(Of T)())
        End Sub

        Public Function EndScope() As BindingTable(Of T)
            Return m_symbolTableStack.Pop()
        End Function

        Public Function Search(ByVal binder As Binder) As T

            'The For Each order on a stack is from top stack to bottom stack.
            'This is just the order we want in symbol searching

            Dim content As T = Nothing
            If CurrentTable.TryLookUp(binder, content) Then
                Return content
            End If

            Return Nothing
        End Function

    End Class

End Namespace
